import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import '../textFiled/kq_textfiled.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 输入组件
///
/// [ItemType.edit]
///
/// @author 周卓
///
/// 结合 KqFormEntity 使用
class KqEditItemView extends StatefulWidget {
  /// 通用属性
  final KqFormEntity entity;

  /// 控件不可编辑时点击回调
  final Function(KqFormEntity entity)? onTap;

  /// 输入控件或选择控件的左侧控件
  final Widget Function(KqFormEntity entity)? customLeftView;

  /// 输入控件或选择控件或自定义控件的右侧控件
  final Widget Function(KqFormEntity entity)? customRightView;

  /// 自定义控件的底部控件
  final Widget Function(KqFormEntity entity)? customBottomView;

  /// 输入变化回调
  final ValueChanged<String>? onChanged;

  /// 焦点变化
  final Function(bool hasFocus)? onFocusChanged;

  const KqEditItemView(
      {Key? key,
      required this.entity,
      this.customLeftView,
      this.customRightView,
      this.customBottomView,
      this.onChanged,
      this.onFocusChanged,
      this.onTap})
      : super(key: key);

  @override
  KqEditItemViewState createState() => KqEditItemViewState();
}

class KqEditItemViewState extends State<KqEditItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;

    if (widget.entity.controller != null &&
        widget.entity.valueForShow != null) {
      TextFiledUtil.setValue(
          widget.entity.controller!, widget.entity.valueForShow!);
    }

    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ?? KqThemeManager.getFormConfig().backgroundColor ?? KqThemeColors.bgWhite;
    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          KqInkWell(
            onTap: () {
              if (widget.entity.onTap != null) {
                widget.entity.onTap!(widget.entity);
              }
              if (widget.onTap != null) {
                widget.onTap!(widget.entity);
              }
            },
            borderWidth: 0,
            child: Container(
              color: widget.entity.showFocusBorder ? null : bgColor,
              padding: EdgeInsets.only(
                  right: widget.entity.paddingHorizontal ??
                      KqThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      16.r),
              decoration: widget.entity.showFocusBorder
                  ? BoxDecoration(
                      color: bgColor,
                      border: Border.all(width: 1, color: KqThemeColors.bgBlue))
                  : null,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    crossAxisAlignment: widget.entity.multiline
                        ? CrossAxisAlignment.baseline
                        : CrossAxisAlignment.center,
                    textBaseline: widget.entity.multiline
                        ? TextBaseline.alphabetic
                        : null,
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.only(right: widget.entity.titleRightMargin ?? (widget.entity.title.isNotEmpty ? 10.r : 0)),
                        margin: EdgeInsets.only(
                            top: widget.entity.paddingVertical ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingVertical ??
                                15.r,
                            bottom: widget.entity.paddingVertical ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingVertical ??
                                15.r),
                        child: Row(
                          children: <Widget>[
                            ///是否必填
                            Container(
                              alignment: Alignment.centerRight,
                              padding: EdgeInsets.only(
                                right: 2.r,
                              ),
                              width: widget.entity.paddingHorizontal ??
                                  KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .paddingHorizontal ??
                                  16.r,
                              child: Text(
                                "∗",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontSize: KqThemeManager.instance
                                            .getConfig()
                                            .formConfig
                                            .mustInputFontSize ??
                                        14.sp,
                                    color: widget.entity.mustInput
                                        ? KqThemeColors.textRed
                                        : KqThemeColors.bgTransparent),
                              ),
                            ),

                            /// 标题
                            LimitedBox(
                              maxWidth: KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .titleMaxWidth ??
                                  200.r,
                              child: Text(
                                widget.entity.title,
                                maxLines: widget.entity.multiline ? null : 1,
                                overflow: widget.entity.multiline
                                    ? null
                                    : TextOverflow.ellipsis,
                                style: widget.entity.titleStyle ??
                                    TextStyle(
                                        fontSize: KqThemeManager.instance
                                                .getConfig()
                                                .formConfig
                                                .titleFontSize ??
                                            16.sp,
                                        color: widget.entity.titleColor ??
                                            KqThemeManager.getFormConfig()
                                                .titleTextColor ??
                                            KqThemeColors.text26),
                              ),
                            )
                          ],
                        ),
                      ),
                      Expanded(
                        /// 输入框
                        child: Row(
                          children: [
                            /// 左边自定义控件
                            /// 自定义布局，来自实体类
                            widget.entity.customLeftView != null
                                ? widget.entity.customLeftView!(widget.entity)
                                : Container(),

                            /// 自定义布局，来自控件
                            widget.customLeftView != null
                                ? widget.customLeftView!(widget.entity)
                                : Container(),
                            // 为了和UI规范的标题和内容之间距离40
                            SizedBox(
                              width: 30.r,
                              height: 1.r,
                            ),
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.symmetric(vertical: 10.r),
                                child: KqTextFiled(
                                  multiline: widget.entity.multiline,
                                  maxLines: widget.entity.maxLines,
                                  inputType: widget.entity.inputType,
                                  editable: widget.entity.isEditable(),
                                  forceShowPlaceHolder:
                                      widget.entity.forceShowPlaceHolder,
                                  controller: widget.entity.controller,
                                  textColor: widget.entity.contentColor,
                                  textInputAction:
                                      widget.entity.textInputAction,
                                  fontSize: KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .contentFontSize,
                                  enableClearButton:
                                      widget.entity.enableClearButton,
                                  textAlign: TextAlign.end,
                                  newValue: widget.entity.valueForShow ?? '',
                                  placeHolder: widget.entity.hint,
                                  maxCharCount: widget.entity.maxCharCount,
                                  onSubmitted: (value) {
                                    widget.entity.valueForShow = value;
                                    widget.entity.valueForSubmit = value;
                                    widget.entity.onSubmitted?.call(value);
                                  },
                                  inputFormatters:
                                      widget.entity.inputFormatters,
                                  onFocusChanged: (hasFocus) {
                                    widget.entity.onFocusChanged
                                        ?.call(hasFocus);
                                    widget.onFocusChanged?.call(hasFocus);
                                  },
                                  onMonitor: (str) {
                                    widget.entity.onMonitor
                                        ?.call(widget.entity, str);
                                  },
                                  onChanged: (text) {
                                    widget.entity.valueForShow = text;
                                    widget.entity.valueForSubmit = text;
                                    widget.entity.onChanged?.call(text);
                                    widget.onChanged?.call(text);
                                  },
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      /// 单位
                      Visibility(
                        visible: widget.entity.unit.isNotNullOrEmpty,
                        child: Container(
                            padding: EdgeInsets.only(
                                left: widget.entity.isEditable() ? 10.r : 4.r,
                                top: widget.entity.paddingVertical ??
                                    KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .paddingVertical ??
                                    15.r,
                                bottom: widget.entity.paddingVertical ??
                                    KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .paddingVertical ??
                                    15.r),
                            child: Text(
                              widget.entity.unit ?? "",
                              style: TextStyle(
                                color: widget.entity.unitColor ??
                                    KqThemeColors.text26,
                                fontSize: KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .unitFontSize ??
                                    16.sp,
                              ),
                            )),
                      ),

                      /// 自定义布局，来自实体类
                      widget.entity.customRightView != null
                          ? widget.entity.customRightView!(widget.entity)
                          : Container(),

                      /// 自定义布局，来自控件
                      widget.customRightView != null
                          ? widget.customRightView!(widget.entity)
                          : Container(),
                    ],
                  ),
                ],
              ),
            ),
          ),

          /// 自定义底部控件，来自实体类
          widget.entity.customBottomView != null
              ? widget.entity.customBottomView!(widget.entity)
              : Container(),

          /// 自定义控件，来自控件
          widget.customBottomView != null
              ? widget.customBottomView!(widget.entity)
              : Container(),

          /// 分割线
          Visibility(
              visible: !widget.entity.hideDivider, child: KqDivider(
            leftMargin: !widget.entity.dividerHorMarginEnable ? 0 : widget.entity.paddingHorizontal ??
                KqThemeManager.instance
                    .getConfig()
                    .formConfig
                    .paddingHorizontal ??
                16.r,
            rightMargin: !widget.entity.dividerHorMarginEnable ? 0 : widget.entity.paddingHorizontal ??
                KqThemeManager.instance
                    .getConfig()
                    .formConfig
                    .paddingHorizontal ??
                16.r,
          ))
        ],
      ),
    );
  }
}
